import React, { useState, useEffect } from 'react';
import { Link } from 'umi';
import { useCallbackState, useDidUpdateEffect } from '../../utils/useHooks';

export default function IndexPage() {
  // ----------------------列表任务切片功能----------------------
  const [num1, setNum1] = useCallbackState(0);
  const [num2, setNum2] = useState(0);

  const [num3, setNum3] = useCallbackState(0);
  let [testNum1, setTestNum1] = useState(0);
  let [testNum2, setTestNum2] = useState(0);

  // -----------------useDidUpdateEffect测试-------------------
  React.useEffect(() => {
    console.log('testNum1变更');
  }, [testNum1]);

  useDidUpdateEffect(() => {
    console.log('testNum2变更');
  }, [testNum2]);

  // ---------普通setState测试-------------------
  function originSetState() {
    setNum2(num2 + 1);
    console.log('setState执行');
  }

  // ---------------带回调的setState--------------------
  function setStateWithCb() {
    setNum1(num1 + 1, (state) => {
      console.log('执行回调' + state);
    });
  }

  // --------回调setState测试------------------
  useEffect(() => {
    console.log('useEffect后执行');
  }, [num3]);

  // ------------异步循环器---------------------
  function asyncCycle() {
    const promiseArray: any[] = [];
    for (var i = 0; i < 10; i++) {
      const promiseItem = new Promise((resolve, reject) => {
        resolve(num1);
      }).then((res) => {});
      promiseArray.push(promiseItem);
    }

    Promise.all(promiseArray).then((resArr) => {
      console.log(resArr);
    });
  }

  function cbAndEffect() {
    setNum3(num3 + 1, () => {
      console.log('回调先执行');
    });
  }

  function testNumAdd() {
    setTestNum1(testNum1 + 1);
    setTestNum2(testNum2 + 1);
  }

  return (
    <div>
      <br />
      <Link to="/home">带回调的setState测试</Link>
      <br />
      <Link to="/longListRender">长列表切片组件测试</Link>
      <br />
      <Link to="/longListTest">长列表切片功能演示</Link>

      <h1>带回调的setState测试</h1>
      <button onClick={originSetState}>普通setState测试 1000times</button>
      <br />

      <button onClick={setStateWithCb}>setStateCallback测试</button>
      <h3>
        说明 因为React底层原因 钩子无法在循环中使用
        所以回调在循环中也只能执行第一次
      </h3>
      <br />

      <button onClick={cbAndEffect}>回调和useEffect调用顺序</button>
      <h3>回调会先执行 useEffect中语句会后执行</h3>
      <br />
      <button onClick={testNumAdd}>useDidUpdateEffect测试</button>
      <h3>说明:首次渲染时 useDidUpdateEffect中逻辑不会执行</h3>
      <br />

      <button onClick={asyncCycle}>异步迭代器测试</button>

      <br />
      <br />
      <br />
      <br />
      <Link to="/home">带回调的setState测试</Link>
      <br />
      <Link to="/longListRender">长列表切片组件测试</Link>
      <br />
      <Link to="/longListTest">长列表切片功能演示</Link>
    </div>
  );
}
